#pragma once
#include <string>
#include <iostream>

#include <sys/stat.h>
/*文件的工具类
    功能:判断文件存在、获取父路径、创建目录
    stat获取文件属性判断文件是否存在
    find'/\\'获取最后一个\
    创建文件:逐层创建,mkdir
*/

namespace ns_helper
{
    class FileUntil
    {
    public:
        static bool IsExists(const std::string &pathname)
        {
            struct stat st;
            return stat(pathname.c_str(), &st) > 0;
        }
        // ./abc/bcd/text.cc
        static std::string FilePath(const std::string &pathname)
        {
            int pos = pathname.find_last_of("/\\");
            if (pos == std::string::npos)
                return ".";
            // 返回 ./abc/bcd/
            return pathname.substr(0, pos + 1);
        }
        // ./abc/cdf/xcv
        static void CreateDirectory(const std::string &pathname)
        {
            if (pathname.empty())
                return;
            if (IsExists(pathname))
                return;
            int pos, index = 0;
            while (index < pathname.size())
            {
                pos = pathname.find_first_of("/\\", index);
                if (pos == std::string::npos)
                {
                    // 创建文件
                    mkdir(pathname.c_str(), 0775);
                    return ;
                }
                std::string currpath = pathname.substr(0, pos + 1);
                if (FileUntil::IsExists(currpath))
                {
                    index = pos + 1;
                    continue;
                }
                // 创建当前路径
                mkdir(currpath.c_str(), 0775);
                index = pos + 1;
            }
        }
    };
};